var app = getApp();

Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    userInfo: "",
    avatar: "",
    thirdAvatar: "",
  },
  onLoad: function() {
    var that = this;
  },
  onShow: function() {
    var that = this;
    //判断token
    if (wx.getStorageSync('token') == '') {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }else{
      that.checkToken()
    }
    that.setData({
      navH: app.globalData.navHeight,
      marH: app.globalData.navHeight + 20,
    })
    if (wx.getStorageSync('token')) {
      that.setData({
        token: wx.getStorageSync('token')
      })
      that.getUserInfo();
    }
  },
  checkToken: function () {
    var that = this;
    wx.request({
      url: app.globalData.apiHost + "/api/token/check",
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'token=' + wx.getStorageSync('token')
      },
      method: "POST",
      dataType: "json",
      success: function (res) {
        if (res.statusCode === 200) {
          console.log(res);
          //监测token是否过期，如果没过期就用缓存取出来的，如果过期就用刷新后的token
          if (res.data.code != 1) {
            that.refreshToken();
          } else {
          }
        }
      }
    });
  },
  refreshToken: function () {
    var that = this;
    wx.request({
      url: app.globalData.apiHost + "/api/token/refresh",
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'token=' + wx.getStorageSync('token')
      },
      method: "POST",
      dataType: "json",
      success: function (res) {
        if (res.statusCode === 200) {
          //刷新后修改全局的token
          wx.setStorageSync('token', res.data.data.token);
        }
      }
    });
  },
  callPhone: function() {
    wx.makePhoneCall({
      phoneNumber: app.globalData.officialPhone,
    })
  },
  getUserInfo: function() {
    var that = this;
    wx.request({
      url: app.globalData.apiHost + "/api/user/info",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'token=' + that.data.token
      },
      method: "POST",
      dataType: "json",
      success: function(res) {
        if (res.statusCode === 200) {
          var userData = res.data.data;
          that.setData({
            userInfo: userData,
            avatar: userData.avatar,
            thirdAvatar: userData.third_avatar
          })
        }
      },

    });
  }
})